package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.constant.RedisMessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.pojo.LoginDTO;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 用户登录
     * @param loginDTO
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginDTO loginDTO){
        // 校验登录验证码的合法性
        Integer validateCode = (Integer) redisTemplate.opsForValue()
                .get(RedisMessageConstant.SENDTYPE_LOGIN + "_" + loginDTO.getTelephone());
        if (validateCode == null ||
                Integer.compare(Integer.valueOf(loginDTO.getValidateCode()), validateCode) != 0){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

        Integer recordCount = memberService.login(loginDTO.getTelephone());

        return new Result(true, MessageConstant.LOGIN_SUCCESS, recordCount);
    }
}
